using System;
using UnityEngine;
using UnityEngine.Events;

namespace General
{
    public class Character : MonoBehaviour
    {
        [Header("事件监听")] public VoidEventSO NewGamEvent;
        [Header("基本属性")] public float maxHealth;
        public float currentHealth;

        [Header("受伤无敌")] public float invulnerableDuration;
        public bool isInvulnerable;
        private float _invulnerableCounter;


        public UnityEvent<Character> OnHealthChange;

        public UnityEvent<Transform> OnTakeDamage;
        public UnityEvent OnDie;

        private void NewGame()
        {
            currentHealth = maxHealth;
            OnHealthChange?.Invoke(this);
        }

        private void OnEnable()
        {
            NewGamEvent.OnEventRaised += NewGame;
        }

        private void OnDisable()
        {
            NewGamEvent.OnEventRaised -= NewGame;
        }

        private void Update()
        {
            if (isInvulnerable)
            {
                _invulnerableCounter -= Time.deltaTime;
                if (_invulnerableCounter <= 0)
                {
                    isInvulnerable = false;
                }
            }
        }

        public void TakeDamage(Attack attacker)
        {
            if (isInvulnerable)
                return;

            if (currentHealth - attacker.damage > 0)
            {
                currentHealth -= attacker.damage;
                TriggerInvulnerable();

                // 触发受伤事件
                OnTakeDamage?.Invoke(attacker.transform);
            }
            else
            {
                currentHealth = 0;
                //TODO: 死亡
                OnDie?.Invoke();
            }

            OnHealthChange?.Invoke(this);
        }

        /// <summary>
        /// 触发受伤无敌
        /// </summary>
        private void TriggerInvulnerable()
        {
            if (!isInvulnerable)
            {
                isInvulnerable = true;
                _invulnerableCounter = invulnerableDuration;
            }
        }
    }
}